package edu.uoc.tdp.pac3.ui.client;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.TitledBorder;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumn;

import edu.uoc.tdp.pac3.beans.Resource;
import edu.uoc.tdp.pac3.beans.ResourceRequest;
import edu.uoc.tdp.pac3.beans.Room;
import edu.uoc.tdp.pac3.client.Client;
import edu.uoc.tdp.pac3.ui.i18n.LanguageUtils;

public class ResolveRequestPanel extends JPanel implements ActionListener{

	private static final long serialVersionUID = 1L;	

	private JButton okRqstButton;
	private Client clientObj;
	private List<ResourceRequest> resRqstList = null;
	private JPanel availables = new JPanel();
	private JPanel noAvailables = new JPanel();
	private JScrollPane availableScroll = null;
	private JScrollPane noAvailableScroll=null;
	private JPanel center = new JPanel();
	
	
	public ResolveRequestPanel(Client client){
		clientObj = client;
		setLayout(new BorderLayout());
		
	
		//Button:
		okRqstButton = new JButton();
        okRqstButton.setText(LanguageUtils.getMessage("client.button.confirmRqst"));
        okRqstButton.addActionListener(this);
        
        center.setLayout(new FlowLayout());
       
        
        //Panell Availables:
        
		availables.setPreferredSize(new Dimension(350, 200));
		availables.setLayout(new BorderLayout());
		TitledBorder border = new TitledBorder(LanguageUtils.getMessage("client.table.possible.title"));
		availables.setBorder(border);
		
		availableScroll = new JScrollPane(getTableQuery1());
		//availableScroll.setSize(350, 200);
		availableScroll.setViewportView(getTableQuery1());
        availableScroll.setColumnHeaderView (getTableQuery1().getTableHeader());
        
        availables.add(availableScroll);
        //Availables al nord
       // this.add(availables, BorderLayout.WEST);
        
        //Panell Not Availables
        
		noAvailables.setLayout(new BorderLayout());	
		TitledBorder border2 = new TitledBorder(LanguageUtils.getMessage("client.table.nonpossible.title"));
		noAvailables.setBorder(border2);
		noAvailables.setPreferredSize(new Dimension(350, 200));
		noAvailableScroll = new JScrollPane(getTableNonPossible());		
		noAvailableScroll.setViewportView(getTableNonPossible());
		noAvailableScroll.setColumnHeaderView (getTableNonPossible().getTableHeader());
		noAvailableScroll.setEnabled(false);
        
		noAvailables.add(noAvailableScroll);


        center.add(availables);
        center.add(noAvailables);
        
        this.add(center,BorderLayout.CENTER);    
        this.add(okRqstButton, BorderLayout.SOUTH);
	}
	
	private void refreshTable(){
		
		availableScroll.setViewportView(getTableQuery1());
        availableScroll.setColumnHeaderView (getTableQuery1().getTableHeader());
        availableScroll.setSize(350, 200);	
        
        noAvailableScroll.setViewportView(getTableNonPossible());
        noAvailableScroll.setColumnHeaderView (getTableNonPossible().getTableHeader());
        noAvailableScroll.setSize(350, 200);	
		
	}
	
	
	
	private JTable getTableQuery1() {
		JTable tableQuery1 = null;
		if (tableQuery1 == null) {
			tableQuery1 = new JTable();
			tableQuery1.setLocation(new Point(0, 0));
			tableQuery1.setSize(new Dimension(100, 180));
			 
			try {
				resRqstList = clientObj.getRemoteObject().getAllResourceRequests();
				ModelAcceptable model = new ModelAcceptable(resRqstList);
				tableQuery1.setModel(model);
				int anchocolumna=0;
				TableColumn columna;
				for (int i=0;i<=3;i++){
					columna = tableQuery1.getColumnModel().getColumn(i);
					
					switch (i){
					case 0: anchocolumna = 30; break;
					case 1: anchocolumna = 20; break;
					case 2: anchocolumna = 20; break;
					case 3: anchocolumna = 20; break;					
					}		
					columna.setPreferredWidth(anchocolumna);
				}  										

			} catch (RemoteException e) {
				JOptionPane.showMessageDialog(null, 
						LanguageUtils.getMessage("client.error.message.remote"),
						LanguageUtils.getMessage("client.error.title"),
						JOptionPane.ERROR_MESSAGE);
			}            
		}
		tableQuery1.setEnabled(false);
		return tableQuery1;
	}
	
	
	private JTable getTableNonPossible() {
		JTable tableQuery1 = null;
		if (tableQuery1 == null) {
			tableQuery1 = new JTable();
			tableQuery1.setLocation(new Point(0, 0));
			tableQuery1.setSize(new Dimension(100, 180));
			List<ResourceRequest> resRqstList = null; 
			try {
				resRqstList = clientObj.getRemoteObject().getNoPossibleRequests();
				ModelAcceptable model = new ModelAcceptable(resRqstList);
				tableQuery1.setModel(model);
				int anchocolumna=0;
				TableColumn columna;
				for (int i=0;i<=3;i++){
					columna = tableQuery1.getColumnModel().getColumn(i);
					
					switch (i){
					case 0: anchocolumna = 30; break;
					case 1: anchocolumna = 20; break;
					case 2: anchocolumna = 20; break;
					case 3: anchocolumna = 20; break;					
					}		
					columna.setPreferredWidth(anchocolumna);
				}  										

			} catch (RemoteException e) {
				JOptionPane.showMessageDialog(null, 
						LanguageUtils.getMessage("client.error.message.remote"),
						LanguageUtils.getMessage("client.error.title"),
						JOptionPane.ERROR_MESSAGE);
			}            
		}
		tableQuery1.setEnabled(false);
		return tableQuery1;
	}
	

    class ModelAcceptable extends AbstractTableModel {
    	private static final long serialVersionUID = 1L;
    	protected Vector<String> listHeaders = new Vector<String>();
    	List<Room> allRooms = null;
    	List<Resource> allResources = null;
       	
    	protected List<ResourceRequest> listRequests = new ArrayList<ResourceRequest>();

    	public ModelAcceptable(List<ResourceRequest> resRqstList) {
    		try{
        		allRooms = clientObj.getRemoteObject().getAllRooms();
        		allResources = clientObj.getRemoteObject().getAllResources();
        	}catch (RemoteException e) {
    			
    		}
    		setHeader();		
    		setAcceptable(resRqstList);   		
    	} 
   	
    	protected void setHeader() { 
    			listHeaders.add(LanguageUtils.getMessage("client.table.header.title1"));
    			listHeaders.add(LanguageUtils.getMessage("client.table.header.title2"));
    			listHeaders.add(LanguageUtils.getMessage("client.table.header.title3"));
    			listHeaders.add(LanguageUtils.getMessage("client.table.header.title4"));
    	}
    	

    	public String getColumnName(int col) {
    	  	return((String)listHeaders.get(col));
    	}
    	
    	private void setAcceptable(List<ResourceRequest> resRqst) {
    		try {
    			for (Iterator<ResourceRequest> it = resRqst.iterator() ; it.hasNext(); ) {
    				ResourceRequest r = it.next();
    				listRequests.add(r);
    			}
    		} catch (Exception e) {
    			System.err.println(e);
    		}
    	}

		public int getColumnCount() {
			return listHeaders.size();
		}

		public int getRowCount() {
			return listRequests.size();
		}

		private String getRoomNameById(int roomId){
			String name = "";
			for(Room room : allRooms){
				if(roomId == room.getIdRoom()){
					name = room.getDescription();
				}
			}
			return name;
		}
		
		private String getResourceNameById(int resId){
			String name = "";
			for(Resource res : allResources){
				if(resId == res.getIdResource()){
					name = res.getName();
				}
			}
			return name;
		}
		
		public Object getValueAt(int rowIndex, int columnIndex) {
			ResourceRequest resRqst = listRequests.get(rowIndex);
			 
				switch (columnIndex) {
					case 0:
						return resRqst.getRequestDate();
					case 1:
						return getRoomNameById(resRqst.getIdRoom());
					case 2:
						return getResourceNameById(resRqst.getIdResource());
					case 3:
						return resRqst.getQuantity();
				}		
				return resRqst;
		}
		
		public boolean isCellEditable(int fila, int columna) {
	    	  return(false);
		}  	
    }

    
	public void actionPerformed(ActionEvent e) {
		if (e.getSource()==okRqstButton) {
			System.out.println("Request confirmed!");
			try {
				if(resRqstList != null && resRqstList.size() >0){
					ResourceRequest request = resRqstList.get(0);
					if(clientObj != null && clientObj.getRemoteObject() != null){
						clientObj.getRemoteObject().finalizeResourceRequest(request.getQuantity(), request.getIdResource(), request.getIdRoom());
						refreshTable();
					}
				}
				
			} catch (RemoteException e1) {
				//Remote Exception: Server error.
				JOptionPane.showMessageDialog(null, 
						LanguageUtils.getMessage("client.error.message.remote"),
						LanguageUtils.getMessage("client.error.title"),
						JOptionPane.ERROR_MESSAGE);
			} catch (Exception e2){
				JOptionPane.showMessageDialog(null, 
						LanguageUtils.getMessage("client.error.message"),
						LanguageUtils.getMessage("client.error.title"),
						JOptionPane.ERROR_MESSAGE);
			}
			
		}
	}
}
